//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//
#import<QuartzCore/QuartzCore.h>
#import "LoginViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
#import "RegisterViewController.h"
#import "OMGToast.h"
#import "SendIdcodeViewController.h"
#import "AppDelegate.h"
#import "MainTabViewController.h"
@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize mainView;
@synthesize edtLoginId;
@synthesize edtPassword;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    edtLoginId.delegate = self;
    edtPassword.delegate = self;
    /*
    mainView.layer.cornerRadius=5;
    mainView.layer.borderWidth=1;
    mainView.layer.borderColor=[UIColor lightGrayColor].CGColor;
    [[mainView layer] setShadowOffset:CGSizeMake(1, 1)];
    [[mainView layer] setShadowRadius:1];
    [[mainView layer] setShadowOpacity:1];
    [[mainView layer] setShadowColor:[UIColor lightGrayColor].CGColor];
    */
    _userView.layer.cornerRadius=3;
    _userView.layer.borderWidth=1;
    _userView.layer.borderColor= TEXTFIELD_COLOR.CGColor;
    _passwordView.layer.cornerRadius=3;
    _passwordView.layer.borderWidth=1;
    _passwordView.layer.borderColor= TEXTFIELD_COLOR.CGColor;

    NSString *mobile = [[Config Instance]getMobile];
    if ((NSNull *)mobile != [NSNull null] && [mobile isEqualToString:@""]==false) {
        edtLoginId.text = mobile;
    }
}

- (void)viewDidUnload
{
    [self setEdtLoginId:nil];
    [self setEdtPassword:nil];
    [self setMainView:nil];
    [self setUserView:nil];
    [self setPasswordView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"登陆";
    }
    return self;
}
- (IBAction)doLogin:(id)sender {
    //登陆验证
    NSString *msg = @"";
    if([edtLoginId.text isEqualToString:@""]){
        msg = @"请输入手机号";
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:msg delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([Config isMobileNumber:edtLoginId.text]==NO ){
        msg = @"您输入的手机号码格式不正确";
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:msg delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([edtPassword.text isEqualToString:@""]){
        msg = @"请输入密码";
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:msg delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

        NSURL *url = [NSURL URLWithString:url_login];
        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
        [request setPostValue: edtLoginId.text forKey:@"member.mobile"];
        [request setPostValue: edtPassword.text forKey:@"member.password"];
        [request setShouldAttemptPersistentConnection:false];
        [request setDelegate: self];
        [request startAsynchronous];
    
    
}

//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
//    NSLog(@"%@",jsonStr);
    NSDictionary *dic = [jsonStr JSONValue];
    
    NSMutableDictionary *member = [dic valueForKey:@"data"];
   // NSLog(@"%@", member);
    if(member == nil || (id)member == [NSNull null]){
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:[dic valueForKey:@"log"]
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];

    }else
    {
        [member setValue:edtPassword.text forKey:@"LoginPass"];
        [[Config Instance] saveLogin:member];
        [self.navigationController popViewControllerAnimated:YES];
    }
    // Use when fetching binary data
    //    NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:APP_TITLE
//                                                   message:net_failure_msg
//                                                 delegate:nil
//                                        cancelButtonTitle:@"确定"
//                                        otherButtonTitles:nil];
//    [alert show];
//    [alert release];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }

}


- (IBAction)doBack:(id)sender {
    MainTabViewController * tab=(MainTabViewController*)[self tabBarController];
    if([tab selectedIndex]!=3)
    {
         [self.navigationController popViewControllerAnimated:YES];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    //    if (theTextField == self.textField) {
    [theTextField resignFirstResponder];
    //    }
    return YES;
}

- (IBAction)doRegister:(id)sender {
    SendIdcodeViewController *view=[[SendIdcodeViewController alloc]initWithNibName:@"SendIdcodeViewController" bundle:nil];
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)resetpwd:(id)sender {
    if([edtLoginId.text isEqualToString:@""] ){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"请先输入手机号码"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([Config isMobileNumber:edtLoginId.text]==NO ){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"您输入的手机号码格式不正确"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSURL *url = [NSURL URLWithString:url_resetpwd];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue: edtLoginId.text forKey:@"member.mobile"];
    [request setDidFinishSelector:@selector(finishRestPwd:)];
    [request setShouldAttemptPersistentConnection:false];
    [request setDelegate: self];
    [request startAsynchronous];
    
        
}
-(void) finishRestPwd:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
//    if([[dic valueForKey:@"status"] isEqualToString:@"ERROR"]){
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
//                            [dic valueForKey:@"log"]
//                                                    delegate:nil
//                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];
//        return;
//    }
    
    if ([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
                            @"密码已重置，请查收短信"
                                                    delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
        
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
                            [dic valueForKey:@"log"]
                                                    delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet *allTouches = [event allTouches];
    
    switch ([allTouches count]) {
        case 1: {
            // potential pan gesture
            [self.edtLoginId resignFirstResponder];
        } break;
    }
}
@end
